package top.lshaci.learning.springboot.jpa.config;

import lombok.extern.slf4j.Slf4j;
import top.lshaci.learning.springboot.jpa.entity.BaseEntity;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.time.LocalDateTime;

/**
 * BaseEntityAuditListener
 * <pre>
 *     1、该 Listener 不会注册为 spring bean,
 *     2、如果要在该 Listener 使用其它 spring bean, 可以使用 static 字段注入的方式
 * </pre>
 *
 * @author liangxu
 */
@Slf4j
public class BaseEntityAuditListener {

    @PrePersist
    public void prePersist(Object obj) {
        pre(obj, true);
    }

    @PreUpdate
    public void preUpdate(Object obj) {
        pre(obj, false);
    }

    private void pre(Object obj, boolean isCreate) {
        if (!(obj instanceof BaseEntity)) {
            log.debug("【{}】不是BaseEntity对象", obj.getClass().getSimpleName());
            return;
        }
        LocalDateTime now = LocalDateTime.now();
        BaseEntity entity = (BaseEntity) obj;
        if (isCreate) {
            entity.setCreator("creator");
            entity.setCreateTime(now);
        }
        entity.setUpdater("updater");
        entity.setUpdateTime(now);
    }
}
